package com.spring.housing.interception;

import com.spring.housing.constant.Constants;


import com.spring.housing.returnType.CommenResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@RefreshScope
@Slf4j
public class MvcInterception implements HandlerInterceptor {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    RedisTemplate redisTemplate;
    @Value("${nacos.intercepter.enable}")
    //拦截器是否启动:true为启动
    Boolean intercepterStatus;
    @Value("${nacos.accessToken.enable}")
    //token令牌是否启动:true为启动
    Boolean accessToken;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean res = true;
        log.info(intercepterStatus?"拦截器启动成功!":"拦截器未启动");
        log.info(accessToken?"Token启动成功!":"Token未启动");
        if(accessToken){
         if(request.getHeader("accessToken")==null){
             log.info("-------请求头accessToken未传入-------");
             return false;
         }
      else{
          if(redisTemplate.opsForValue().get("accessToken")==null){
              log.info("-------无法从Redis访问accessToken-------");
          return false;
          }
             List<Map<String, Object>> maps = jdbcTemplate.queryForList("select accessToken from access_token where id =1 and DATE_FORMAT(date,'%Y-%m-%d')=DATE_FORMAT(sysdate(),'%Y-%m-%d')");
         if(!redisTemplate.opsForValue().get("accessToken").toString().equals(request.getHeader("accessToken"))){
             log.info("-------accessToken失效 有效期为一天-------");
             return false;
         }
             log.info(redisTemplate.opsForValue().get("accessToken").toString());
                 res=  true;
      }
        }

        if (intercepterStatus) {
            Object userName = redisTemplate.opsForValue().get(Constants.LOGINSESSION == null ? "xxxxxx" : Constants.LOGINSESSION);
//￥
            if (userName != null) {
                return  true;
            } else {
                log.info("登录信息失效请重新登录!");
                response.sendRedirect(request.getContextPath() + "/login");
            }

        }
        if(!accessToken && !intercepterStatus)
        {
            log.info("accessToken与intercepter未启动");
            res = true;
        }
        return res;

    }


}


